﻿using System;
using System.Net;
using LitJson;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using UnityEngine;
using Model;

namespace Hotfix
{
    public class HTTPRequset : Singleton<HTTPRequset>
    {

        public HttpWebRequest httpWeb;
        /// <summary>
        /// HTTP请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url">Url地址</param>
        /// <param name="obj">数据</param>
        /// <returns></returns>
        public async Task<T> HttpRespuestAsync<T>(string url, object obj)
        {
            string data = JsonMapper.ToJson(obj);
            string asset = await Respuest(url, data);
            if (asset != null)
            {
                T objData = LitJson.JsonMapper.ToObject<T>(data);
                return objData;
            }
            return default(T);
        }
        /// <summary>
        /// HTTP请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url">Url地址</param>
        /// <param name="obj">数据</param>
        /// <param name="action"></param>
        public void HttpRespuest<T>(string url, object obj, Action<T> action)
        {
            string data = JsonMapper.ToJson(obj);
            HttpRespuest<T>(url, obj, action);
        }
        /// <summary>
        /// HTTP请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url">Url地址</param>
        /// <param name="data">数据</param>
        /// <param name="action"></param>
        public async void HttpRespuest<T>(string url, string data, Action<T> action)
        {
            string asset = await Respuest(url, data);
            if (asset != null)
            {
                T objData = LitJson.JsonMapper.ToObject<T>(asset);
                action(objData);
            }
        }

        private async Task<string> Respuest(string url, string data)
        {
            try
            {
                httpWeb = WebRequest.Create(url) as HttpWebRequest;
                httpWeb.Method = "POST";
                Encoding encoding = Encoding.UTF8;
                byte[] dataBytes = encoding.GetBytes(data);
                httpWeb.GetRequestStream().Write(dataBytes, 0, dataBytes.Length);
                HttpWebResponse webResponse = (HttpWebResponse)httpWeb.GetResponse();
                StreamReader reader = new StreamReader(webResponse.GetResponseStream(), Encoding.GetEncoding("utf-8"));
                string asset = await reader.ReadToEndAsync();
                return asset;
            }
            catch (Exception e)
            {
                Debug.LogError(e);
                throw new Exception(e.ToString());
            }

        }
    }
}
